package leetcode.数组;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 合并区间
 *
 * 解法：就是先按照 start 值排序，然后逐个遍历合并start值小于等于前一个一维数组的 end值的两个区间
 */
public class Test56合并区间 {

    static class Interval {
        int start;
        int end;

        Interval() {
            start = 0;
            end = 0;
        }

        Interval(int s, int e) {
            start = s;
            end = e;
        }

        @Override
        public String toString() {
            return "[" + start + "," + end + "]";
        }
    }

    public static List<Interval> merge(List<Interval> intervals) {
        if (intervals == null || intervals.size() == 0 || intervals.size() == 1) {
            return intervals;
        }
        int n = intervals.size();
        int[] starts = new int[n];
        int[] ends = new int[n];
        for (int i = 0; i < n; i++) {
            starts[i] = intervals.get(i).start;
            ends[i] = intervals.get(i).end;
        }
        Arrays.sort(starts);
        Arrays.sort(ends);
        int i = 0;
        List<Interval> res = new ArrayList<>();
        while (i < n) {
            int st = starts[i];
            // 排序后，找到开始点 > 结束点 的 i，然后重新组织区间
            while (i < n - 1 && starts[i + 1] <= ends[i])
                i++;
            int en = ends[i];
            res.add(new Interval(st, en));
            i++;
        }
        return res;
    }

    public static int[][] merge(int[][] intervals) {
        if (intervals.length < 2)
            return intervals;
        // 根据左边的起点升序排序
        Arrays.sort(intervals, (x, y) -> x[0] - y[0]);
        List<int[]> ans = new ArrayList<>();
        ans.add(intervals[0]);
        for (int i = 1; i < intervals.length; i++) {
            int[] cur = intervals[i];
            int[] last = ans.get(ans.size() - 1);
            if (cur[0] <= last[1]) {
                // 若发现当前遍历的数组的开始值 <= ans里面最后一个数组的结束值
                // 就说明这两个数组发生了交集，需要更新ans里面的 end 值为最大值
                last[1] = Math.max(last[1], cur[1]);
                ans.remove(ans.size() - 1);
                ans.add(last);
            } else {
                ans.add(cur);
            }
        }
        return ans.toArray(new int[ans.size()][2]);
    }


    public static void main(String[] args) {
//        Interval i1 = new Interval(1, 4);
//        Interval i2 = new Interval(2, 3);
//        List<Interval> intervals = new ArrayList<>();
//        intervals.add(i1);
//        intervals.add(i2);
//        System.out.println(merge(intervals));

        int[][] intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
        int[][] ans = merge(intervals);
        for (int[] a : ans) {
            System.out.println(Arrays.toString(a));// [[1,6],[8,10],[15,18]]
        }
    }
}
